package lg.minecraft.plugin.testeconomy.storage.model;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import lg.minecraft.plugin.testeconomy.TestEconomy;
import lg.minecraft.plugin.testeconomy.storage.FileStorage;
import lg.minecraft.plugin.testeconomy.storage.StorageType;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author langle__
 * @version 1.0
 */
public class JSONStorage extends FileStorage {

    private static final Gson gson = new GsonBuilder()
            .setPrettyPrinting()
            .create();

    private final File file;
    private JsonObject json;

    public JSONStorage() {
        this.file = new File(TestEconomy.getManiConfig().getJsonPath());
        this.json = new JsonObject();
    }

    @Override
    public StorageType getType() {
        return StorageType.JSON;
    }

    @Override
    protected Double getMoney(String playerName) {
        if (json.has(playerName)) {
            return json.get(playerName).getAsDouble();
        }
        return null;
    }

    @Override
    protected void setMoney(String playerName, double amount) {
        json.add(playerName, new JsonPrimitive(String.valueOf(amount)));
        asyncSave();
    }

    @Override
    protected List<String> getPlayers() {
        if (json == null || json.isJsonNull()) {
            return Collections.emptyList();
        }

        return new ArrayList<>(json.keySet());
    }

    @Override
    public void save() {
        try (FileWriter writer = new FileWriter(file)) {
            gson.toJson(json, writer);
        } catch (IOException e) {
            TestEconomy.getInstance().getLogger().warning("Failed to save storage.json");
        }
    }

    @Override
    public void load() {
        if (!file.exists()) return;
        try (FileReader reader = new FileReader(file)) {
            json = gson.fromJson(reader, JsonObject.class);
        } catch (IOException e) {
            TestEconomy.getInstance().getLogger().warning("Failed to load storage.json");
        }
    }

}
